package com.hanbang.taitaigou.ui.widget.banner;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v4.view.ViewPager.PageTransformer;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.utils.other.ObjectUtils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 页面翻转控件，极方便的广告栏
 * 支持无限循环，自动翻页，翻页特效
 *
 * @author Sai 支持自动翻页
 */
public class ConvenientBanner<T> extends LinearLayout {
    private static long DEFAULT_TIME = 6000;
    private List<T> mDatas;
    /**
     * 0 ： 选中
     * 1：未选
     */
    private int[] pageIndicatorColor = {Color.RED, Color.GRAY};
    /**
     * 点间距 像素
     */
    private int pageIndicatorSeparation = 3;
    private int circleRadius = 4;
    private int widthScroll = 0;
    private int heightScroll = 0;
    private ArrayList<CircleDotsView> mPointViews = new ArrayList<CircleDotsView>();
    private CBPageAdapter pageAdapter;
    private CBLoopViewPager viewPager;
    private ViewGroup loPageTurningPoint;
    private long autoTurningTime;
    private boolean turning;
    private boolean canTurn = false;
    private boolean canLoop = true;

    public enum PageIndicatorAlign {
        ALIGN_PARENT_LEFT, ALIGN_PARENT_RIGHT, CENTER_HORIZONTAL
    }

    private AdSwitchTask adSwitchTask;

    static class AdSwitchTask implements Runnable {

        private final WeakReference<ConvenientBanner> reference;

        AdSwitchTask(ConvenientBanner convenientBanner) {
            this.reference = new WeakReference<ConvenientBanner>(convenientBanner);
        }

        @Override
        public void run() {
            ConvenientBanner convenientBanner = reference.get();

            if (convenientBanner != null) {
                if (convenientBanner.viewPager != null && convenientBanner.turning) {
                    int page = convenientBanner.viewPager.getCurrentItem() + 1;
                    convenientBanner.viewPager.setCurrentItem(page);
                    convenientBanner.postDelayed(convenientBanner.adSwitchTask, convenientBanner.autoTurningTime);
                }
            }
        }
    }


    public ConvenientBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ConvenientBanner);
        canLoop = a.getBoolean(R.styleable.ConvenientBanner_canLoop, true);
        pageIndicatorColor[0] = a.getColor(R.styleable.ConvenientBanner_circleColorSelect, pageIndicatorColor[0]);
        pageIndicatorColor[1] = a.getColor(R.styleable.ConvenientBanner_circleColorDef, pageIndicatorColor[1]);
        pageIndicatorSeparation = a.getDimensionPixelSize(R.styleable.ConvenientBanner_separation, ObjectUtils.dip2px(context, pageIndicatorSeparation));
        circleRadius = a.getDimensionPixelSize(R.styleable.ConvenientBanner_radius, ObjectUtils.dip2px(context, circleRadius));
        widthScroll = a.getInteger(R.styleable.ConvenientBanner_widthScroll, widthScroll);
        heightScroll = a.getInteger(R.styleable.ConvenientBanner_heightScroll, heightScroll);
        init(context);
        setPageIndicatorAlign(PageIndicatorAlign.CENTER_HORIZONTAL);
    }

    private void init(Context context) {
        View hView = LayoutInflater.from(context).inflate(
                R.layout.convenient_banner, this, true);
        viewPager = (CBLoopViewPager) hView.findViewById(R.id.cbLoopViewPager);
        loPageTurningPoint = (ViewGroup) hView
                .findViewById(R.id.loPageTurningPoint);
        adSwitchTask = new AdSwitchTask(this);
    }

    public ConvenientBanner setPages(CBViewHolderCreator holderCreator, List<T> datas) {
        this.mDatas = datas;
        pageAdapter = new CBPageAdapter(getContext(), holderCreator, mDatas);
        setPageIndicator(pageIndicatorColor);
        viewPager.setAdapter(pageAdapter, mPointViews, pageIndicatorColor, canLoop);

        return this;
    }

    /**
     * 通知数据变化
     */

    public void notifyDataSetChanged() {
        setPageIndicator(pageIndicatorColor);
        viewPager.getAdapter().notifyDataSetChanged();
    }

    /**
     * 设置底部指示器是否可见
     *
     * @param visible
     */
    public ConvenientBanner setPointViewVisible(boolean visible) {
        loPageTurningPoint.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (widthScroll != 0 && heightScroll != 0) {
            getLayoutParams().height = getMeasuredWidth() * heightScroll / widthScroll;
        }
    }

    public void setWidthAndHeight(int widthScroll, int heightScroll) {
        this.widthScroll = widthScroll;
        this.heightScroll = heightScroll;
        if (widthScroll != 0 && heightScroll != 0) {
            invalidate();
        }

    }

    /**
     * 底部指示器
     */
    public ConvenientBanner setPageIndicator(int[] pageIndicatorColor) {
        LayoutParams layoutParams = new LayoutParams(circleRadius * 2, circleRadius * 2);
        layoutParams.setMargins(pageIndicatorSeparation, 0, pageIndicatorSeparation, 0);//4个参数按顺序分别是左上右下
        this.pageIndicatorColor = pageIndicatorColor;
        mPointViews.clear();
        loPageTurningPoint.removeAllViews();
        if (mDatas == null) return this;
        for (int count = 0; count < mDatas.size(); count++) {
            // 翻页指示的点
            CircleDotsView pointView = new CircleDotsView(getContext());
            pointView.setLayoutParams(layoutParams);
            pointView.setRadius(circleRadius);
            pointView.setCircleColor(pageIndicatorColor[1]);
            mPointViews.add(pointView);
            loPageTurningPoint.addView(pointView);
        }
        return this;
    }

    /**
     * dp
     */
    public void setCircleRadius(int circleRadius) {
        this.circleRadius = ObjectUtils.dip2px(getContext(), circleRadius);
        setPageIndicator(pageIndicatorColor);

    }

    public void setPageIndicatorSeparation(int pageIndicatorSeparation) {
        this.pageIndicatorSeparation = ObjectUtils.dip2px(getContext(), pageIndicatorSeparation);
        setPageIndicator(pageIndicatorColor);
    }

    /**
     * 指示器的方向
     *
     * @param align 三个方向：居左 （RelativeLayout.ALIGN_PARENT_LEFT），居中 （RelativeLayout.CENTER_HORIZONTAL），居右 （RelativeLayout.ALIGN_PARENT_RIGHT）
     * @return
     */
    public ConvenientBanner setPageIndicatorAlign(PageIndicatorAlign align) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) loPageTurningPoint.getLayoutParams();
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, align == PageIndicatorAlign.ALIGN_PARENT_LEFT ? RelativeLayout.TRUE : 0);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, align == PageIndicatorAlign.ALIGN_PARENT_RIGHT ? RelativeLayout.TRUE : 0);
        layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, align == PageIndicatorAlign.CENTER_HORIZONTAL ? RelativeLayout.TRUE : 0);
        loPageTurningPoint.setLayoutParams(layoutParams);
        return this;
    }

    /***
     * 是否开启了翻页
     *
     * @return
     */
    public boolean isTurning() {
        return turning;
    }

    /***
     * 开始翻页
     *
     * @param autoTurningTime 自动翻页时间
     * @return
     */
    public ConvenientBanner startTurning(long autoTurningTime) {
        //如果是正在翻页的话先停掉
        if (turning) {
            stopTurning();
        }
        if (mDatas.size() > 1) {
            //设置可以翻页并开启翻页
            canTurn = true;
            this.autoTurningTime = autoTurningTime;
            turning = true;
            postDelayed(adSwitchTask, autoTurningTime);
        } else {
            canTurn = false;
            turning = false;
        }


        return this;
    }

    public void stopTurning() {
        turning = false;
        removeCallbacks(adSwitchTask);
    }

    public ConvenientBanner startTurning() {
        return startTurning(DEFAULT_TIME);
    }

    /**
     * 自定义翻页动画效果
     *
     * @param transformer
     * @return
     */
    public ConvenientBanner setPageTransformer(PageTransformer transformer) {
        viewPager.setPageTransformer(true, transformer);
        return this;
    }


    public boolean isManualPageable() {
        return viewPager.isCanScroll();
    }

    public void setManualPageable(boolean manualPageable) {
        viewPager.setCanScroll(manualPageable);
    }

    //触碰控件的时候，翻页应该停止，离开的时候如果之前是开启了翻页的话则重新启动翻页
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        int action = ev.getAction();
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_OUTSIDE) {
            // 开始翻页
            if (canTurn) startTurning(autoTurningTime);
        } else if (action == MotionEvent.ACTION_DOWN) {
            // 停止翻页
            if (canTurn) stopTurning();
        }
        return super.dispatchTouchEvent(ev);
    }

    //获取当前的页面index
    public int getCurrentItem() {
        if (viewPager != null) {
            return viewPager.getCurrentItem();
        }
        return -1;
    }

    //设置当前的页面index
    public void setcurrentitem(int index) {
        if (viewPager != null) {
            viewPager.setCurrentItem(index);
        }
    }


    public boolean isCanLoop() {
        return viewPager.isCanLoop();
    }

    public CBLoopViewPager getViewPager() {
        return viewPager;
    }

    public void setCanLoop(boolean canLoop) {
        this.canLoop = canLoop;
        viewPager.setCanLoop(canLoop);
    }


}
